# Copyright (C) 2013-2015 Ragpicker Developers.
# This file is part of Ragpicker Malware Crawler - http://code.google.com/p/malware-crawler/

import json
import logging
import httplib2
import urllib

from core.database import Database
from core.abstracts import Processing
from utils.multiPartForm import MultiPartForm

try:
    from yapsy.IPlugin import IPlugin
except ImportError:
    raise ImportError, 'Yapsy (Yet Another Plugin System) is required to run this program : http://yapsy.sourceforge.net'

log = logging.getLogger("ProcessingBlueCoatMAA")

MAA_SANDBOX_NAME = "BlueCoatMAA"
MAA_TASK_STATE_START = "IVM_INPROCESS"
MAA_SAMPLE_CREATE_URL = 'https://%s/rapi/samples/basic?token=%s'
MAA_TASK_CREATE_URL = 'https://%s/rapi/tasks?token=%s'

class BlueCoatMAA(IPlugin, Processing):
    
    def run(self, objfile):
        self.key = "BlueCoatMAA"
        self.score = -1
        host = self.options.get("host")
        port = self.options.get("port")
        timeout = self.options.get("timeout", 120)
        apikey = self.options.get("apikey")
        owner = self.options.get("user")
        https = self.options.get("https")
        database = Database()
        
        returnValue = {}
        
        if not host or not port or not apikey or not owner:
            raise Exception("BlueCoatMAA is not configured correctly")
        
        try:                
            fileName = objfile.file.get_fileSha256()
            file_data = objfile.file.file_data
            
            message = MultiPartForm()
            message.add_file_data('unused', filename=fileName, file_data=file_data, mimetype='application/octet-stream')
            message.add_field('owner', owner)
        
            headers = {'Content-type': message.get_content_type()}
            h = httplib2.Http()
            protocol = "http"
            
            if https:
                protocol = "https"
                h = httplib2.Http(".cache", disable_ssl_certificate_validation=True)
                
            response, content = h.request('%s://%s:%s/rapi/samples/basic?token=%s' % (protocol, host, port, apikey), "PUT", 
                                          body=message.toBlueCoatString(), headers=headers)      
            
            if not "'status': '200'" in str(response) :
                log.error(str(content))
                raise Exception(str(content)) 
                
            data = json.loads(content)
            sample_id = data['results'][0]['samples_sample_id']
            log.info("%s upload as new sample_id %d" % (fileName, sample_id))
        
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
            parameters = {}
            parameters["sample_id"] = sample_id
            parameters["env"] = 'ivm'
            parameters["log_task"] = 1
            parameters["tp_IVM.TIMEOUT"] = timeout
        
            response, content = h.request('%s://%s:%s/rapi/tasks?token=%s' % (protocol, host, port, apikey), 'PUT', 
                                          body=urllib.urlencode(parameters), headers=headers)
        
            if not "'status': '200'" in str(response) :
                log.error(str(content))
                raise Exception(str(content))        
        
            data = json.loads(content)
            task_id = data['results'][0]['tasks_task_id']
            log.info("new task_id %d" % task_id)
            
            returnValue = {"sample_id":sample_id, "task_id":task_id}
            
            #Insert Task-State-Report
            database.insertSandboxTaskStatus(sandboxName=MAA_SANDBOX_NAME, sha256=objfile.file.get_fileSha256(), 
                                             taskID=task_id, sampleID=sample_id, taskState=MAA_TASK_STATE_START)
        except Exception as e:
            raise Exception("Failed to send the file to the BlueCoatMAA: %s" % e)
        
        return returnValue